#include "asm/system.h"
#include "string.h"

char* strcpy(char* dest, const char* src)
{
    char* ptr = dest;
    while(*src)
    {
        *ptr++ = *src++;
    }
    *ptr = '\0';
    return dest;
}

size_t strlen(const char* str)
{
    size_t len = 0;
    while (*str++) 
    {
        len++;
    }
    return len;
}

int strcmp(const char* lhs, const char* rhs)
{
    while (*lhs == *rhs && *lhs && *rhs)
    {
        lhs++;
        rhs++;
    }
    
    if (*lhs > *rhs)
    {
        return 1;
    } else if (*lhs < *rhs)
    {
        return -1;
    } else
    {
        return 0;
    }
}

char* strchr(const char* str, int ch)
{
    while (*str)
    {
        if (*str == ch)
        {
            return str;
        }
        str++;
    }
    return NULL;
}

char* strrchr(const char* str, int ch)
{
    char* end;
    size_t len = strlen(str);
    end = str + len - 1;
    while (end >= str)
    {
        if (*end == ch)
        {
            return end;
        }
        end--;
    }
    return NULL;
}

int memcmp(const void *lhs, const void* rhs, size_t count)
{
    char* lptr = (char*) lhs;
    char* rptr = (char*) rhs;
    while (count--)
    {
        if (*lptr > *rptr)
        {
            return 1;
        } 
        else if (*lptr < *rptr)
        {
            return -1;
        }
        lptr++;
        rptr++;
    }
    return 0;
}

void* memset(void* dest, int ch, size_t count)
{
    char* ptr = dest;
    while (count--)
    {
        *ptr++ = (char) ch;
    }
    return dest;
}

void* memcpy(void* dest, const void* src, size_t count)
{
    char* dest_ptr = (char*) dest;
    char* src_ptr = (char*) src;
    while (count--)
    {
        *dest_ptr++ = *src_ptr++;
    }
    return dest;
}

void* memchr(const void* str, int ch, size_t count)
{
    char *ptr = (char*) str;
    while (count--)
    {
        if (*ptr == ch)
        {
            return (void*) ptr;
        }
        ptr++;
    }
    return NULL;
}